<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="line-height: 36px;">客户管理</span>
        <el-button style="float: right;" type="primary" @click="dialogOpen('add')" v-if="USER.auth.indexOf('addCustom')!==-1">新增客户</el-button>
      </div>
      <s-table :table="table" @http="tableWatch">
        <el-form-item slot="multiSelect" label="多选操作" prop="multiSelect" v-if="table.multiSelect">
          <el-row>
            <el-col :span="8">
              <el-button size="small" type="danger" @click="tableMultiDelete" v-if="USER.auth.indexOf('deleteCustom')!==-1">多选删除</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-table-column
          fixed="right"
          slot="operation"
          align="center"
          label="可用操作"
          width="100">
          <template scope="s">
            <el-button type="info" icon="edit" size="mini" @click="tableEdit(s.row)" v-if="USER.auth.indexOf('modCustom')!==-1"></el-button>
            <el-button type="danger" icon="delete" size="mini" @click="tableDelete(s.row)" v-if="USER.auth.indexOf('deleteCustom')!==-1"></el-button>
          </template>
        </el-table-column>
        <el-form-item label="客户名称" prop="name">
          <el-input type="text"
                    class="input"
                    v-model="autoVueTable_name"
                    placeholder="客户名称" spellcheck="false" auto-capitalize="off" auto-complete="off"
                    auto-correct="off"></el-input>
        </el-form-item>
      </s-table>
    </el-card>

    <s-dialog :dialog="dialog" :close="dialogInit">
      <p slot="title">{{dialog.title}}<span>{{formDialog.id ? ('客户编码：' + formDialog.rentcode) : ''}}</span></p>
      <s-form :form="formDialog" ref="formDialog">
        <el-row>
          <el-col :xs="24" :lg="{span: 10, offset: 0}">
            <el-form-item prop="name" label="客户名称">
              <el-input type="text"
                        v-model="formDialog.name"
                        placeholder="客户名称" spellcheck="false" auto-capitalize="off" auto-complete="off"
                        auto-correct="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 10, offset: 2}">
            <el-form-item prop="rentcode" label="客户编码">
              <el-input type="text"
                        v-model="formDialog.rentcode"
                        placeholder="客户编码" spellcheck="false" auto-capitalize="off" auto-complete="off"
                        auto-correct="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 10, offset: 0}">
            <el-form-item prop="type" label="客户性质">
              <el-select v-model="formDialog.type">
                <el-option
                  v-for="item in CUSTOM.type"
                  :key="item.dictionaryid"
                  :label="item.value"
                  :value="item.dictionaryid">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 10, offset: 2}">
            <el-form-item prop="trades" label="所属行业">
              <el-select v-model="formDialog.trades" multiple>
                <el-option
                  v-for="item in CUSTOM.trades"
                  :key="item.dictionaryid"
                  :label="item.value"
                  :value="item.dictionaryid">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 10, offset: 0}">
            <el-form-item prop="scale" label="机构规模">
              <el-select v-model="formDialog.scale">
                <el-option
                  v-for="item in CUSTOM.scale"
                  :key="item.dictionaryid"
                  :label="item.value"
                  :value="item.dictionaryid">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 10, offset: 2}">
            <el-form-item prop="descr" label="客户简介">
              <el-input type="textarea"
                        :autosize="{ minRows: 1, maxRows: 2}"
                        v-model="formDialog.descr"
                        placeholder="备注" spellcheck="false" auto-capitalize="off" auto-complete="off"
                        auto-correct="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 10, offset: 0}">
            <el-form-item prop="address" label="客户地址">
              <el-input type="textarea"
                        :autosize="{ minRows: 1, maxRows: 2}"
                        v-model="formDialog.address"
                        placeholder="备注" spellcheck="false" auto-capitalize="off" auto-complete="off"
                        auto-correct="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 10, offset: 2}">
            <el-form-item prop="netstation" label="客户网站">
              <el-input type="text"
                        v-model="formDialog.netstation"
                        placeholder="客户网站" spellcheck="false" auto-capitalize="off" auto-complete="off"
                        auto-correct="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </s-form>
      <el-button slot="footer" @click="dialogSave">保存</el-button>
    </s-dialog>
  </div>
</template>

<script>
  import {AutoVue} from '~/plugins/Tools';

  function __form () {
    return {
      name: {
        value: '',
        rule: [
          'vNull',
        ],
        notes: '客户名称',
      },
      netstation: {
        value: '',
        notes: '客户网站',
      },

      type: {
        value: 1,
        notes: '客户性质',
      },
      trades: {
        value: [1],
        rule: [
          'vNull',
        ],
        notes: '所属行业',
      },

      scale: {
        value: 1,
        notes: '机构规模',
      },
      createtime: {
        value: '',
        notes: '创建日期',
      },

      descr: {
        value: '',
        notes: '客户简介',
      },
      address: {
        value: '',
        notes: '客户地址',
      },

      id: {
        value: 0,
        notes: '客户ID',
      },
      rentcode: {
        value: '',
        notes: '客户编码',
        rule: 'vNull',
      },
    };
  }

  export default AutoVue({
    name: 'custom-safety',
    transition: 'slide-fade',
    store: ['DICTIONARY_custom', 'USER', 'CUSTOM'],
    data: {
      table: {
        column: [
          {
            label: '客户名称',
            prop: 'name',
            minWidth: '0px',
            search: true,
          },
          {
            label: '客户编码',
            prop: 'rentcode',
            minWidth: '0px',
            search: true,
          },
          {
            label: '客户性质', // type
            prop: 'typename',
            minWidth: '0px',
            search: true,
          },
          {
            label: '所属行业', // ,见字典表,可以多选，dictionary接口 trades
            prop: 'trade',
            minWidth: '0px',
            search: true,
          },
          {
            label: '客户规模',
            prop: 'scalename',
            minWidth: '0px',
            search: true,
          },
          {
            label: '客户地址',
            prop: 'address',
            minWidth: '0px',
            search: true,
          },
          {
            label: '客户简介',
            prop: 'descr',
            minWidth: '0px',
            search: true,
          },
          {
            label: '客户网站',
            prop: 'netstation',
            minWidth: '0px',
            search: true,
          },
          {
            label: '创建日期',
            prop: 'createtime',
            formatter: (row, column) => {
              return this.a.methods.formatterTime(row[column.property || column], 1);
            },
            minWidth: '0px',
            search: true,
          },
        ],
        url: '/custom/',
        key: 'id',
        tableColumn: 5,
      },
      formDialog: __form(),
      dialog: {
        title: '新增',
      },
    },
    methods: {
      tableEdit (row) {
        this.dialogOpen('PUT', row);
      },
      tableDelete (row) {
        this.$confirm('您将删除客户。', '确认删除？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        })
          .then(async _ => {
            try {
              await this.post('/custom/delete/', [row.id]);
              this.tableWatch('table');
            } catch (err) {
              console.log(err);
            }
          })
          .catch(_ => {
          });
      },
      tableMultiDelete () {
        this.$confirm('您将删除这些客户。', '确认删除？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        })
          .then(async _ => {
            let step = [];
            for (let item of this.table.multipleSelection) {
              step.push(item.id);
            }
            try {
              await this.post('/custom/delete/', step);
              this.tableWatch('table');
            } catch (err) {
              console.log(err);
            }
          })
          .catch(_ => {
          });
      },

      dialogInit () {
        this.formDialog = {
          ...this.formDialog,
          ...this.ObjectClone(__form()),
        };
        this.resetFields('formDialog');
      },
      async dialogOpen (type, more) {
        if (type) {
          type = type.toUpperCase();
        } else return;
        if (!this.DICTIONARY_custom) {
          await this.USE('DICTIONARY_custom');
        }
        switch (type) {
        case 'ADD':
          this.dialog.title = '新增';
          this.formDialog.id = 0;
          break;
        case 'PUT':
          this.dialog.title = '修改';
          for (let index in this.formDialog) {
            if (this.formDialog.hasOwnProperty(index)) {
              if (index === 'trades') {
                let step = [];
                let a = more.trades.split(',');
                for (let index of a) {
                  step.push(parseInt(index));
                }
                this.formDialog[index] = step;
              } else if (typeof more[index] !== 'undefined') {
                this.formDialog[index] = more[index];
              }
            }
          }
          break;
        }
        this.dialog.visible = true;
      },
      dialogSave () {
        // let more = this.dialog.saveParameter;
        if (this.dialog.title === '新增') {
          this.VALIDATE('formDialog', async option => {
            let step = '';
            for (let index of option.trades) {
              step += index + ',';
            }
            option.trades = step.substring(0, step.length - 1);
            try {
              let {id} = await this.post('/custom/add', option);
              let json = await this.get('custom/' + id);
              this.table.data = [json[0], ...this.table.data];
              this.table.total++;
              this.resetFields('formDialog');
              this.dialog.visible = false;
            } catch (err) {
              console.log(err);
            }
          });
        } else {
          this.VALIDATE('formDialog', async option => {
            let step = '';
            for (let index of option.trades) {
              step += index + ',';
            }
            option.trades = step.substring(0, step.length - 1);
            try {
              await this.post('/custom/add', option);
              let id = option.id;
              let json = await this.get('custom/' + id);
              for (let i = 0; i < this.table.data.length; i++) {
                if (this.table.data[i].id === id) {
                  for (let index in this.table.data[i]) {
                    if (this.table.data[i].hasOwnProperty(index)) {
                      this.table.data[i][index] = json[0][index];
                    }
                  }
                }
              }
              this.dialog.visible = false;
            } catch (err) {
              console.log(err);
            }
          });
        }
      },
    },
    mounted: function () {
      this.tableWatch('table');
    },
  });
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
  .box-card {
    margin: 20px;
  }

  .createTimeSpan {
    display: block;
    margin-top: 34px;
  }

  @media screen and (max-width: 800px) {
    .createTimeSpan {
      margin-top: 0;
    }
    .box-card {
      margin: 0;
    }
  }

  .el-select {
    width: 100%;
  }
</style>
